<?php
namespace Api\Utils;

/**
 * Class Xml
 * @package Api\Utils
 */
class Xml
{
    /**
     * @param $name
     * @param $value
     * @param null $default
     * @return null|string
     */
    public static function element($name, $value, $default = null)
    {
        if ($value !== null)
        {
            return '<' . $name . '>' . $value . '</' . $name . '>';
        }
        else if ($default !== null)
        {
            return '<' . $name . '>' . $default . '</' . $name . '>';
        }

        return null;
    }

    /**
     * @param $xml
     * @return array
     */
    public static function xmlToArray($xml)
    {
        $result = array();

        if ($xml->hasChildNodes())
        {
            $child  = $xml->childNodes->item(0);

            // Top document attributes
            foreach ($child->attributes as $attribute)
            {
                $result[$attribute->name] = $attribute->value;
            }

            // Root element items
            foreach ($child->childNodes as $element)
            {
                if ($element instanceof \DOMElement)
                {
                    $result[$child->nodeName][] = self::xmlElementToArray($element);
                }
                else
                {
                    $result[$child->nodeName] = array();
                }
            }
        }

        return $result;
    }

    /**
     * @param \DOMNode $node
     * @return array|string
     */
    public static function xmlElementToArray(\DOMNode $node)
    {
        $array = array();

        if ($node->hasChildNodes())
        {
            /**
             * @var \DOMElement $child
             */
            foreach ($node->childNodes as $child)
            {
                $value = self::xmlElementToArray($child);

                if ($child->nodeType == XML_ELEMENT_NODE)
                {
                    $array[$child->nodeName] = $value;
                }
                else
                {
                    return $child->nodeValue;
                }
            }
        }
        else
        {
            return $node->nodeValue;
        }

        return $array;
    }
}